package com.ews.onlineexchange.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.lang.time.DateFormatUtils;

import net.sf.json.JSONNull;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.CycleDetectionStrategy;

/**
 * @author Administrator
 *当使用BeanUtils时，当遇到date类型的数据项时，需要使用此项
 */
public class MyJsonConfig {
	
	public static JsonConfig getConfig() {
		  //日期转换
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
      //第二种日期转换  
        jsonConfig.registerJsonValueProcessor(java.util.Date.class, new JsonValueProcessor() {
            @Override
          public Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) {
                // TODO Auto-generated method stub
                //导包import org.apache.commons.lang.time.DateFormatUtils; jar包：commons-lang-2.6.jar
            	if(null == arg1) return null;
                 return DateFormatUtils.format((Date)arg1, "yyyy-MM-dd HH:mm:ss");
             }
             
             @Override
            public Object processArrayValue(Object arg0, JsonConfig arg1) {
                 // TODO Auto-generated method stub
                 return null;
             }
         });
        return jsonConfig;
	
	}
	
	public static void dateConvert() {
		ConvertUtils.register(new Converter()
        {
            @SuppressWarnings("rawtypes")
            @Override
            public Object convert(Class arg0, Object arg1)
            {
            	System.out.println("dsd="+arg1);
                if(arg1 == null || arg1 instanceof JSONNull)
                {	
                	
                    return null;
                }
                if(!(arg1 instanceof String))
                {
                    throw new ConversionException("只支持字符串转换 !");
                }
                 
                String str = (String)arg1;
                if(str.trim().equals(""))
                {
                    return null;
                }
                 
                SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                 
                try{
                    return sd.parse(str);
                }
                catch(ParseException e)
                {
                    throw new RuntimeException(e);
                }
                 
            }
             
        }, java.util.Date.class);
	}		
}
